<?php
/**
 * 说明.
 * User: dxk <1024114660@qq.com>
 * Date: 2023/11/2
 */
namespace App\Library\Service\AliCloud;

use AlibabaCloud\SDK\Cloudauth\V20190307\Models\Id2MetaVerifyRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Exception;

class CloudAuth
{
    public static function createClient(): \AlibabaCloud\SDK\Cloudauth\V20190307\Cloudauth
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => config('sys.aliyun.accessKeyId'),
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => config('sys.aliyun.accessSecret')
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Cloudauth
        $config->endpoint = "cloudauth.aliyuncs.com";
        return new \AlibabaCloud\SDK\Cloudauth\V20190307\Cloudauth($config);
    }

    /**
     * 身份证二要素认证
     * @param $userName
     * @param $identifyNum
     * @return array
     */
    public static function Id2MetaVerify($userName, $identifyNum): array
    {
        $params = [
            "paramType" => "normal",
            "userName" => $userName,
            "identifyNum" => $identifyNum,

        ];
        $request = new Id2MetaVerifyRequest($params);
        $client = self::createClient();
        $runtime = new RuntimeOptions([]);
        $runtime->readTimeout = 5000;
        $runtime->connectTimeout = 5000;
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->id2MetaVerifyWithOptions($request, $runtime);
            unset($params['identifyNum']);//防止信息泄露
            easy_log('alicloud/cloudauth', ['action' => 'Id2MetaVerify', 'options' => $params, 'res' => $response]);
            $body = json_decode(json_encode($response, JSON_UNESCAPED_UNICODE), true);
            if ($response->body->code != 200) {
                return alert_info($response->body->code != 0 ? $response->body->code : 1, $response->body->message, $body);
            } else {
                $bizCode = $response->body->resultObject->bizCode;
                if ($bizCode == 1) {
                    return alert_info(0, '校验⼀致', $body);
                } elseif ($bizCode == 2) {
                    return alert_info(2, '校验不⼀致', $body);
                } elseif ($bizCode == 3) {
                    return alert_info(3, '查⽆记录', $body);
                } else {
                    return alert_info(4, '认证异常', $body);
                }
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            return alert_info(1, $error->message);
        }
    }
}
